package vn.personal.anhht.bloback12.block;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class OnBootBlock extends BroadcastReceiver {
    public static void setAlarm(Context ctxt) {
        Log.e("On Boot Block", "Enter setAlarm");
        AlarmManager mgr = (AlarmManager) ctxt
                .getSystemService(Context.ALARM_SERVICE);
        AlarmManager mgr1 = (AlarmManager) ctxt
        .getSystemService(Context.ALARM_SERVICE);
        Calendar cal = Calendar.getInstance();
        Calendar cal1 = Calendar.getInstance();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(ctxt);
        String time = prefs.getString("alarm_time1", "12:00");
        String time1 = prefs.getString("alarm_time2", "12:00");
        cal.set(Calendar.HOUR_OF_DAY, TimePreference.getHour(time));
        cal.set(Calendar.MINUTE, TimePreference.getMinute(time));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal1.set(Calendar.HOUR_OF_DAY, TimePreference.getHour(time1));
        cal1.set(Calendar.MINUTE, TimePreference.getMinute(time1));
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        if (cal.getTimeInMillis() < System.currentTimeMillis() && cal1.getTimeInMillis() < System.currentTimeMillis()) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            cal1.add(Calendar.DAY_OF_YEAR, 1);
        }

        mgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, getPendingIntent(ctxt));
        mgr1.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, getPendingIntent1(ctxt));
    }

    public static void cancelAlarm(Context ctxt) {
        AlarmManager mgr = (AlarmManager) ctxt
                .getSystemService(Context.ALARM_SERVICE);

        mgr.cancel(getPendingIntent(ctxt));
        mgr.cancel(getPendingIntent1(ctxt));
    }

    private static PendingIntent getPendingIntent(Context ctxt) {
        Log.e("On Boot Block", "1111111111111111111");
        Intent i = new Intent(ctxt, TestAlarm.class);
        return (PendingIntent.getBroadcast(ctxt, 0, i, 0));
    }
    
    private static PendingIntent getPendingIntent1(Context ctxt) {
        Log.e("On Boot Block", "222222222222222");
        Intent i = new Intent(ctxt, TestAlarm2.class);
        return (PendingIntent.getBroadcast(ctxt, 0, i, 0));
    }

    @Override
    public void onReceive(Context ctxt, Intent intent) {
        Log.e("On Boot Block", "Enter OnBootBlock");
        setAlarm(ctxt);
    }
}